package com.example.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageSerializable;
import com.example.entity.Classes;
import com.example.entity.Student;
import com.example.entity.StudentExample;
import com.example.mapper.ClassesMapper;
import com.example.mapper.StudentMapper;
import com.example.service.StudentService;
import com.example.util.PageResult;
import com.example.vo.StudentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClassesMapper classesMapper;

    @Override
    public List<Student> findAll() {
        List<Student> students = studentMapper.selectByExample(null);
        students.forEach(st -> {
            Classes classes = classesMapper.selectByPrimaryKey(st.getCid());
            st.setCname(classes.getCname());
        });
        return students;
    }

    // 分页查询
    @Override
    public PageResult<Student> findByPage(Integer page, Integer pageSize) {
        //1. 开始分页
        PageHelper.startPage(page,pageSize);
        // 2. 开始查询数据
        List<Student> students = this.findAll();
        // 3. 将查询得到的数据转换为Page<Student>对象
        Page<Student> studentPage = (Page<Student>) students;
        // 4. 转换为PageResult对象
        return new PageResult<>(studentPage.getResult(),studentPage.getTotal());

    }

    // 条件查询带分页功能
    @Override
    public PageResult<Student> search(Integer page,Integer pageSize,StudentVO studentVo) {
        // 1. 开始分页
        PageHelper.startPage(page, pageSize);
        // 2. 查询数据
        // 2.1 定义一次查询的实例
        StudentExample example = new StudentExample();
        // 2.2 添加查询条件到查询实例中
        StudentExample.Criteria criteria = example.createCriteria();
        if(StrUtil.isNotBlank(studentVo.getSname())){
            criteria.andSnameLike("%" + studentVo.getSname() + "%");
        }
        if(StrUtil.isNotBlank(studentVo.getAddr())){
            criteria.andAddrLike("%" + studentVo.getAddr() + "%"); // addr like '%' + addr + '%'
        }
        if(studentVo.getCid() != null && studentVo.getCid() != 0){
            criteria.andCidEqualTo(studentVo.getCid());
        }
        List<Student> students = studentMapper.selectByExample(example);
        // 2.3 处理学生班级
        students.forEach(st -> {
            Classes classes = classesMapper.selectByPrimaryKey(st.getCid());
            st.setCname(classes.getCname());
        });

        // 2.4 将上面的students对象转换为List集合
        Page<Student> studentPage = (Page<Student>) students;
        return new PageResult<>(studentPage.getResult(),studentPage.getTotal());

    }

    // 3. 添加学生
    @Override
    public boolean save(Student student) {
        return studentMapper.insert(student) > 0;
    }
}
